package com.simple.jdbc.core.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.simple.jdbc.core.io.Resources;
import com.simple.jdbc.core.pojo.Configuration;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;
import java.util.Properties;

public class XMLConfigBuilder {

    private Configuration configuration;

    public XMLConfigBuilder() {
        this.configuration = new Configuration();
    }

    /**
     * 使用 dom4j+xpath 解析配置文件 封装Configuration对象
     * @param inputStream
     * @return
     */
    public Configuration parse(InputStream inputStream) throws DocumentException {

        //xml文档对象
        Document document = new SAXReader().read(inputStream);
        //根节点
        Element rootElement = document.getRootElement();

        List<Node> list = rootElement.selectNodes("//property");
        //<property name="driverClassName" value="com.mysql.cj.jdbc.Driver"></property>
        Properties properties = new Properties();
        for (Node node : list) {
            Element element = (Element) node;
            String name = element.attributeValue("name");
            String value = element.attributeValue("value");
            properties.setProperty(name,value);
        }

        //创建数据源对象  使用数据库连接池
        DruidDataSource druidDataSource = new DruidDataSource();

        /**
         *
         <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"></property>
         <property name="url" value="jdbc:mysql://192.168.113.201:3306/lottery?allowPublicKeyRetrieval=true"></property>
         <property name="username" value="root"></property>
         <property name="password" value="admin123"></property>
         */
        druidDataSource.setDriverClassName(properties.getProperty("driverClassName"));
        druidDataSource.setUrl(properties.getProperty("url"));
        druidDataSource.setUsername(properties.getProperty("username"));
        druidDataSource.setPassword(properties.getProperty("password"));

        configuration.setDataSource(druidDataSource);

        //映射配置解析
        /**
         *     <mappers>
         *         <mapper reource="mapper/UserMapper.xml"></mapper>
         *     </mappers>
         */
        //路径获取
        List<Node> mapperList = rootElement.selectNodes("//mapper");
        for (Node node : mapperList) {
            Element element = (Element) node;
            //文件加载并解析
            String resourcePath = element.attributeValue("resource");
            InputStream resourceAsStream = Resources.getResourceAsStream(resourcePath);
            XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(configuration);

            xmlMapperBuilder.parse(resourceAsStream);

        }




        //封装MappedStatement对象  存入Configuration的map集合



        return configuration;
    }



}
